requirejs([
    './js/init',
    './js/Imagery',
    './js/Popup',
    './js/Column',
    './js/MeasureTool'
    //'./js/Test'
],
    function (
        init,
        Imagery,
        Popup,
        columns,
        MeasureTool,
        createHeatMapInCesium
    ) {
        var viewer = init.viewer;
        var toolBar = init.toolBar;
        var position = init.position;
        var geocoder = new Cesium.Geocoder({
            container: 'search',
            scene: viewer.scene
        })


        /****************************************************
         *                      图层部分
         ****************************************************/
        toolBar.addToolBar('000', '修改图层', function(){
            var layers = viewer.scene.imageryLayers;
            var imagery = new Imagery();
            // 图层
            var layersToSelect = [{
                name : '必应',
                value : 'bing'
            },{
                name : 'esri',
                value : 'esri'
            },{
                name : 'OSM',
                value : 'osm'
            },{
                name : 'mapbox图层',
                value : 'mapbox'
            },{
                name : '移除图层',
                value : 'none'
            }]
            var popup = new Popup('popup000', document.getElementById('cesiumContainer'), '修改图层', 100);
            popup.addSelect('图层', 'imagery', layersToSelect);
            popup.addRange('透明度', 'opacity', 0, 100);
            popup.addRange('光照', 'light', 0, 100);
            popup.addButton('确认修改',function(){
                var values = popup.getInputsValue();
                layers.removeAll();
                // 修改图层
                if(values.imagery !== 'none'){
                    layers.addImageryProvider(imagery[values.imagery]);
                }
                // 修改图层透明度
                if(layers.length>0){
                    layers.get(layers.length - 1).alpha = parseFloat(values.opacity/100);
                    layers.get(layers.length - 1).brightness = parseFloat(values.light/100);
                }
            })
            popup.lock();
            popup.show();
        });
        /*
        toolBar.addToolBar('003', 'gee图层', function(){
            layers.addImageryProvider(imagery.gee);
        });
        */

        /*
        toolBar.addToolBar('005', 'ino图层', function(){
            layers.addImageryProvider(imagery.ino);
        });
        */

        

        /****************************************************
         *                    添加标注点
         ****************************************************/
        var mousePositionOnWSG;
        toolBar.addToolBar('0012', '添加标注', function () {
            // 绑定事件
            var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);

            handler.setInputAction(function () {
                // 获取鼠标点击坐标
                mousePositionOnWSG = position.mousePositionOnWSG;
                // 弹窗
                var popup = new Popup('popup1', document.getElementById('cesiumContainer'), '添加标注', 100);
                if (!popup.locked) {
                    // 构造颜色数组
                    var colors = [{
                        name: '蓝色',
                        value: 0,
                        realValue: Cesium.Color.BLUE
                    }, {
                        name: '灰色',
                        value: 1,
                        realValue: Cesium.Color.GRAY
                    }, {
                        name: '黑色',
                        value: 2,
                        realValue: Cesium.Color.BLACK
                    }, {
                        name: '绿色',
                        value: 3,
                        realValue: Cesium.Color.GREEN
                    }, {
                        name: '黄色',
                        value: 4,
                        realValue: Cesium.Color.YELLOW
                    }];
                    popup.addInput('提示信息', 'markInfo', '不超过两字');
                    popup.addInput('标注名称', 'markName');
                    popup.addSelect('颜色', 'markColor', colors);
                    popup.addButton(['确认添加', '清空输入'], [function () {
                        // 获取弹窗数据
                        var values = popup.getInputsValue();

                        // 添加标注
                        var mark = viewer.entities.add({
                            name: values.markName,
                            position: Cesium.Cartesian3.fromDegrees(mousePositionOnWSG.x, mousePositionOnWSG.y),
                            billboard: {
                                image: new Cesium.PinBuilder().fromText(values.markInfo, colors[parseInt(values.markColor)].realValue, 48).toDataURL(),
                                verticalOrigin: Cesium.VerticalOrigin.BOTTOM
                            }
                        });
                        // 关闭弹窗
                        popup.close();
                    }, function () {
                        popup.clearInputs();
                    }])
                    popup.show();
                    popup.lock();
                }
                // 移除事件
                handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        });
        var rotateEarth;
        var x = 0;
        toolBar.addToolBar('0014', '地球旋转', function () {
            if (typeof rotateEarth === 'function') {
                return
            }
            rotateEarth = function () {
                x = x + 0.3;
                if (x >= 178.5) {
                    x = -180
                }
                viewer.scene.camera.setView({
                    destination: new Cesium.Cartesian3.fromDegrees(x, 30, 16000000)
                });
            }
            viewer.clock.onTick.addEventListener(rotateEarth);
        });
        toolBar.addToolBar('0015', '停止旋转', function () {
            if (typeof rotateEarth === 'function') {
                viewer.clock.onTick.removeEventListener(rotateEarth);
                rotateEarth = undefined;
            }
        });
        toolBar.addToolBar('0016', '天津模型', function () {
            var promise = Cesium.GeoJsonDataSource.load('/src/data/tianjin.json', {
                stroke: false,
                strokeWidth: 0,
            });

            promise.then(function (dataSource) {
                viewer.dataSources.add(dataSource);

                // 获取entities数组
                var entities = dataSource.entities.values;

                for (var i = 0; i < entities.length; i++) {
                    var entity = entities[i];
                    entity.name = 'Entity ' + i;
                    entity.polygon.outline = false;
                    // 设置透明度
                    if (entity.properties.H < 5) {
                        entity.polygon.material = Cesium.Color.FORESTGREEN;
                    } else if (entity.properties.H < 10) {
                        entity.polygon.material = Cesium.Color.DARKORANGE;
                    } else {
                        entity.polygon.material = Cesium.Color.CORNSILK;
                    }

                    // 设置高度
                    entity.polygon.extrudedHeight = entity.properties.H * 8;
                }
                viewer.flyTo(dataSource.entities);
            }).otherwise(function (error) {
                window.alert(error);
            });
        });
        toolBar.addToolBar('0017', '框选范围', function () {
            var begin = {},
                end = {};
            var count = 0;
            var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
            handler.setInputAction(function () {
                switch (count) {
                    case 0:    // 第一次点击
                        var mousePositionOnWSG = position.mousePositionOnWSG;
                        begin.x = mousePositionOnWSG.x;
                        begin.y = mousePositionOnWSG.y;
                        count++;
                        break;

                    case 1:    // 第二次点击
                        var mousePositionOnWSG = position.mousePositionOnWSG;
                        end.x = mousePositionOnWSG.x;
                        end.y = mousePositionOnWSG.y;
                        // 获取坐标
                        var west, south, east, north;
                        if (begin.x > end.x) {
                            east = begin.x;
                            west = end.x
                        } else {
                            east = end.x;
                            west = begin.x
                        }
                        if (begin.y > end.y) {
                            north = begin.y;
                            south = end.y
                        } else {
                            north = end.y;
                            south = begin.y
                        }

                        // 移动视角
                        var rectangle = new Cesium.Rectangle.fromDegrees(west, south, east, north);
                        viewer.camera.flyTo({
                            destination: rectangle
                        });

                        // 移除事件
                        handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
                        count = 0;
                        break;

                    default:
                        // 移除事件
                        handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
                        count = 0;
                        break;
                }
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        });
        toolBar.addToolBar('0018', '路线绘制', function () {

        });
        toolBar.addToolBar('0019', '距离量算', function () {
            var mt = new MeasureTool();
            mt.measureDistance()
        });
        toolBar.addToolBar('0020', '攻击效果', function () {

        });
        toolBar.addToolBar('0021', '热力图', function () {
            createHeatMapInCesium()
        });
        toolBar.addToolBar('0022', '人口分布图', function () {
            var entities = viewer.entities;
            for (var i = 0; i < columns.length; i++) {
                entities.add(columns[i]);
            }
        });
        toolBar.addToolBar('0023', '撤销分布图', function () {
            var entities = viewer.entities;
            for (var i = 0; i < columns.length; i++) {
                entities.remove(columns[i]);
            }
        });
        var begin = {},
            end = {},
            distance = 300000;
        toolBar.addToolBar('0024', '圆形范围', function () {

            var count = 0;
            var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
            handler.setInputAction(function () {
                switch (count) {
                    case 0:    // 第一次点击
                        var mousePositionOnWSG = position.mousePositionOnWSG;
                        begin.x = mousePositionOnWSG.x;
                        begin.y = mousePositionOnWSG.y;
                        count++;
                        break;

                    case 1:    // 第二次点击
                        var mousePositionOnWSG = position.mousePositionOnWSG;
                        end.x = mousePositionOnWSG.x;
                        end.y = mousePositionOnWSG.y;
                        var startCartographic = Cesium.Cartographic.fromDegrees(begin.x, begin.y);
                        var endCartographic = Cesium.Cartographic.fromDegrees(end.x, end.y);
                        var geodesic = new Cesium.EllipsoidGeodesic();
                        geodesic.setEndPoints(startCartographic, endCartographic);
                        distance = geodesic.surfaceDistance;
                        var popup = new Popup('popup2', document.getElementById('cesiumContainer'), '圆形范围', 100);
                        if (!popup.locked) {
                            var colors = [{
                                name: '蓝色',
                                value: 0,
                                realValue: Cesium.Color.BLUE
                            }, {
                                name: '灰色',
                                value: 1,
                                realValue: Cesium.Color.GRAY
                            }, {
                                name: '黑色',
                                value: 2,
                                realValue: Cesium.Color.BLACK
                            }, {
                                name: '绿色',
                                value: 3,
                                realValue: Cesium.Color.GREEN
                            }, {
                                name: '黄色',
                                value: 4,
                                realValue: Cesium.Color.YELLOW
                            }];
                            var alpha = [{
                                name: '0.1',
                                value: 0.1,
                            }, {
                                name: '0.3',
                                value: 0.3,
                            }, {
                                name: '0.5',
                                value: 0.5,
                            }, {
                                name: '0.7',
                                value: 0.7,
                            }, {
                                name: '0.9',
                                value: 0.9,
                            }]
                            popup.addInput('范围名称', 'markName');
                            popup.addSelect('范围颜色', 'markColor', colors);
                            popup.addSelect('透明度', 'markAlpha', alpha);
                            popup.addButton(['确认添加', '清空输入'], [function () {
                                // 获取弹窗数据
                                var values = popup.getInputsValue();

                                viewer.entities.add({
                                    position: Cesium.Cartesian3.fromDegrees(begin.x, begin.y, 0.0),
                                    name: values.markName,
                                    ellipse: {
                                        semiMinorAxis: distance,
                                        semiMajorAxis: distance,
                                        height: 0,
                                        material: colors[values.markColor].realValue.withAlpha(parseFloat(values.markAlpha)),
                                        outline: false, // height must be set for outline to display
                                        heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
                                    }
                                });
                                // 关闭弹窗
                                popup.close();
                            }, function () {
                                popup.clearInputs();
                            }]);
                            popup.show();
                            popup.lock();
                        }
                        // 移除事件
                        handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
                        count = 0;
                        break;

                    default:
                        // 移除事件
                        handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
                        count = 0;
                        break;
                }
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        })
        toolBar.addToolBar('0025', '添加模型', function () {
            var entity = viewer.entities.add({
                name: '一个模型',
                position: Cesium.Cartesian3.fromDegrees(-123.0744619, 44.0503706),
                model: {
                    uri: '/src/data/shuinuan.gltf',
                    minimumPixelSize: 0,
                    maximumScale: 20000,
                    color: Cesium.Color.RED
                }
            });
            entity.description = `
            <p>模型描述,可嵌入HTML代码</p>
        `;
            var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
            viewer.camera.flyTo({
                destination: Cesium.Cartesian3.fromDegrees(-123.074681, 44.0470360, 300.0),
                orientation: {
                    heading: Cesium.Math.toRadians(0.0),
                    pitch: Cesium.Math.toRadians(-45.0),
                    roll: 0.0
                }
            });
            //viewer.camera.moveBackward(4000)
        });
        var classifcationTilesetUrl = '/src/data/Batchedguiyang1/tileset.json';
        // A b3dm tileset used to classify the photogrammetry tileset
        var classificationTileset = new Cesium.Cesium3DTileset({
            url: classifcationTilesetUrl,
            classificationType: Cesium.ClassificationType.CESIUM_3D_TILE
        });
        toolBar.addToolBar('0026', '3D Tiles', function () {
            var popup = new Popup('popup1', document.getElementById('cesiumContainer'), '添加标注', 100);
            if (!popup.locked) {
                var tilesets = [{
                    name: 'Batchedbarrel',
                    value: '/src/data/Batchedbarrel/tileset.json',
                }, {
                    name: 'allbatched',
                    value: '/src/data/allbatched/tileset.json',
                }, {
                    name: 'wlm',
                    value: '/src/data/Batchedwlm/tileset.json',
                }, {
                    name: 'tujian',
                    value: '/src/data/Batchedtujian/tileset.json',
                }, {
                    name: 'guiyang',
                    value: '/src/data/Batchedguiyang1/tileset.json',
                }, {
                    name: 'Tileset',
                    value: '/src/data/Tileset/tileset.json',
                }, {
                    name: 'shuinuan',
                    value: '/src/data/Batchedshuinuan/tileset.json',
                }];
                popup.addSelect('3D Tile', 'tile', tilesets);
                popup.addButton('确认添加', function () {
                    // 获取弹窗数据
                    var values = popup.getInputsValue();

                    var url = values.tile;
                    var tileSet = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
                        url: url,
                        skipLevelOfDetail: true,
                        baseScreenSpaceError: 1024,
                        skipScreenSpaceErrorFactor: 16,
                        skipLevels: 1,
                        immediatelyLoadDesiredLevelOfDetail: false,
                        loadSiblings: false,
                        cullWithChildrenBounds: true
                    }));

                    tileSet.readyPromise.then(function (tileset) {
                        viewer.camera.viewBoundingSphere(tileset.boundingSphere, new Cesium.HeadingPitchRange(0, -0.5, 0));
                        viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
                        var scene = viewer.scene;
                    
                        var ellipsoid = scene.globe.ellipsoid;
                        var cart  = ellipsoid.cartesianToCartographic(tileSet.boundingSphere.center);
                        var h
                        console.log();
                        console.log(tileSet.boundingSphere.radius)

                        var terrainProvider = Cesium.createWorldTerrain();
                        var positions = [
                            cart
                        ];
                        var promise = Cesium.sampleTerrain(terrainProvider, 11, positions);
                        Cesium.when(promise, function(updatedPositions) {
                            console.log(ellipsoid.cartesianToCartographic(tileSet.boundingSphere.center) - positions[0].height);
                            var height = positions[0].height;
                            var cartographic = Cesium.Cartographic.fromCartesian(tileSet.boundingSphere.center);
                            var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
                            var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, height);
                            var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
                            tileSet.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
                        });
                    });
                    

                    var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
                    var div = document.createElement('div');
                    document.getElementById('cesiumContainer').appendChild(div);
                    div.style = 'width: 300px;word-break: break-all;background-color:#666;padding:5px;position:absolute;top:80px;right:10px;color:#fff;border-radius:2px';
                    var last;
                    handler.setInputAction(function () {
                        var pick = viewer.scene.pick(position.mousePositionOnScreen);
                        if (pick && pick != last) {
                            div.innerText = pick.getProperty('name').split(' ')[0];
                            pick.color = Cesium.Color.RED;
                            if (last) {
                                last.color = Cesium.Color.WHITE;
                            }
                            last = pick;
                        } else {
                            if (last) {
                                last.color = Cesium.Color.WHITE;
                            }
                        }
                    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
                    var height = 0;
                    handler.setInputAction(function(val){
                    
                        height += 1;
                        var cartographic = Cesium.Cartographic.fromCartesian(tileSet.boundingSphere.center);
                        var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
                        var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, height);
                        var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
                        tileSet.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
                    },Cesium.ScreenSpaceEventType.RIGHT_CLICK);
                    // 关闭弹窗
                    popup.close();
                })
                popup.show();
                popup.lock();
            }
        })
        toolBar.addToolBar('0027', '隐藏要素', function () {
            var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
            handler.setInputAction(function () {
                var pick = viewer.scene.pick(position.mousePositionOnScreen);
                if (pick) {
                    pick.show = false;
                }
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        })
        toolBar.addToolBar('0028', '停止隐藏', function () {
            var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
            handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
        })
        toolBar.addToolBar('0029', '移动相机视角', function () {
            var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
            var scene = viewer.scene;
            handler.setInputAction(function (movement) {
                var feature = scene.pick(movement.position);
                if (!Cesium.defined(feature)) {
                    return;
                }

                zoom(movement, feature);




                function zoom(movement, feature) {
                    var pickedObject = scene.pickPosition(movement.position);
                    var cartographic = Cesium.Cartographic.fromCartesian(pickedObject);
                    var longitude = cartographic.longitude;
                    var latitude = cartographic.latitude;
                    var height = cartographic.height;
                    // var longitude = Cesium.Math.toRadians(feature.getProperty('longitude'));
                    // var latitude = Cesium.Math.toRadians(feature.getProperty('latitude'));
                    // var height = feature.getProperty('height');

                    var positionCartographic = new Cesium.Cartographic(longitude, latitude, height);
                    var position = scene.globe.ellipsoid.cartographicToCartesian(positionCartographic);

                    var camera = scene.camera;
                    var heading = camera.heading;
                    var pitch = camera.pitch;

                    var offset = offsetFromHeadingPitchRange(heading, pitch, height * 2.0);

                    var transform = Cesium.Transforms.eastNorthUpToFixedFrame(position);
                    Cesium.Matrix4.multiplyByPoint(transform, offset, position);

                    camera.flyTo({
                        destination: position,
                        orientation: {
                            heading: heading,
                            pitch: pitch
                        },
                        easingFunction: Cesium.EasingFunction.QUADRATIC_OUT
                    });
                }

                function offsetFromHeadingPitchRange(heading, pitch, range) {
                    pitch = Cesium.Math.clamp(pitch, -Cesium.Math.PI_OVER_TWO, Cesium.Math.PI_OVER_TWO);
                    heading = Cesium.Math.zeroToTwoPi(heading) - Cesium.Math.PI_OVER_TWO;

                    var pitchQuat = Cesium.Quaternion.fromAxisAngle(Cesium.Cartesian3.UNIT_Y, -pitch);
                    var headingQuat = Cesium.Quaternion.fromAxisAngle(Cesium.Cartesian3.UNIT_Z, -heading);
                    var rotQuat = Cesium.Quaternion.multiply(headingQuat, pitchQuat, headingQuat);
                    var rotMatrix = Cesium.Matrix3.fromQuaternion(rotQuat);

                    var offset = Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_X);
                    Cesium.Matrix3.multiplyByVector(rotMatrix, offset, offset);
                    Cesium.Cartesian3.negate(offset, offset);
                    Cesium.Cartesian3.multiplyByScalar(offset, range, offset);
                    return offset;
                }
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

        })
    });
